package com.qf.servlet;

import com.qf.pojo.Cart;
import com.qf.pojo.CartItem;
import com.qf.pojo.Product;
import com.qf.pojo.User;
import com.qf.service.ProductService;
import com.qf.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cart")
public class CartServlet extends BaseServlet{
    //作用:将购物车实体--存储在Session域中
    //购物车应该存储在Session域中(存储在服务器端)
    //定义一个方法:不管是将购物车项添加购物车/将购物车项从购物车中删除/清空购物车 都需要从session中获取购物车
    public Cart getCart(HttpServletRequest request){
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //判断
        if (cart== null){
            //创建新的购物车实体
            cart = new Cart();
            //Session中存储("cart",cart)
            request.getSession().setAttribute("cart",cart);
        }
        return cart;
    }
    public void add2Cart(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //先判断用户是否登录过
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            //没有登录过
            //请求转发到登录页面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }
        //获取隐藏域提交的pid
        String pid = request.getParameter("pid");
        //调用商品的业务接口,获取指定的商品实体
        ProductService productService = new ProductServiceImpl();
        Product product = productService.getProduct(pid);

        //获取商品数量参数
        String countNum = request.getParameter("count");
        //转换int类型
        int count = Integer.parseInt(countNum);

        //获取购物车
        Cart cart = getCart(request);

        //将购物车项加入购物车
        //封装购物车项
        CartItem cartItem = new CartItem(product,count);
        cart.addCartItem2Cart(cartItem);
        System.out.println(cart);

        //重定向购物车页面
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");

    }
    //从购物车中删除购物车项
    public void delCartItem(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //	window.location.href="${pageContext.request.contextPath}/cart?methodName=delCartItem&pid="+pid
        String pid = request.getParameter("pid");
        //获取购物车
        Cart cart = getCart(request);
        //调用的购物车的删除购物车项的方法
        cart.clearCartItemFromCart(pid);
        //重定向到购物车页面
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }
    //清空购物车
    public void clear(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //获取购物车
        Cart cart = getCart(request);
        //调用的购物车的清空购物车的方法
        cart.clear();
        //重定向到购物车页面
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }
}
